package com.oocl.ita.linstner.chatframe;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JTextArea;

import com.oocl.ita.qqclientt.QQClient;
import com.oocl.ita.sakura.client.Client;
import com.oocl.ita.sakura.protocol.Protocol;

public class SendListener implements ActionListener {
	/*
	 * 1. 点击"send" 按钮时，组装"chat" Protocol， from to 从JList中获取 content 
	 * 2. oos 发送
	 * 
	 * 3. 清空输入框
	 */
	private JTextArea jta;

	public SendListener(JTextArea jta) {
		super();
		this.jta = jta;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		System.out.println("SendListener : "  + QQClient.getClient() + " click \"send\" button");

		// 获取输入框的内容， 封装报文
		String content = jta.getText();
		Protocol protocol = new Protocol("chat");		
		Client fromClient = QQClient.getClient();
		Client toClient = QQClient.getToClient();			// 如果用直接引用static变量就错了，new一个就对了
		protocol.encapsulate("from", fromClient);
		protocol.encapsulate("to", new Client(QQClient.getToClient().getAccout()));
		System.err.println("SendListener" + toClient );
		protocol.encapsulate("content", content);
		System.out.println("SendListener : send "  + QQClient.getClient() + " " +protocol);

		// 发送 1.获取oos 2.发送
		System.out.println("SendListener : "  + QQClient.getClient() + " send chat protocol");
		try {
			QQClient.getOos().writeObject(protocol);
			System.err.println("SendListener : after send to server " + protocol);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		// 清空输入框
		jta.setText("");
	}

}
